package com.example.wuyeguanli.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.example.wuyeguanli.R;
import com.example.wuyeguanli.entiy.Complaint;
import com.example.wuyeguanli.entiy.Response;
import com.example.wuyeguanli.tools.ApiClient;
import com.example.wuyeguanli.tools.DataValidator;
import com.example.wuyeguanli.tools.GlideApp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ComplaintSuggestionActivity extends AppCompatActivity {
    private final String TAG = "ApiClient";
    private Button btnBack, btnSubmit, newBtnSelectImage;
    private EditText telephone, complaintsText;
    private ProgressBar loadingProgress;
    private ImageView newImagePreview;
    private final ApiClient apiClient = new ApiClient();

    private Uri selectedImageUri = null;
    private String selectedImageFileName = null;

    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) pickImageFromGallery();
                else Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
            });

    private final ActivityResultLauncher<String> pickImageLauncher =
            registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> {
                if (uri != null) {
                    this.selectedImageUri = uri;
                    this.selectedImageFileName = getFileNameFromUri(uri);
                    GlideApp.with(this).load(uri).into(newImagePreview);
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaintsuggestion);
        if(getSupportActionBar() != null) getSupportActionBar().hide();

        initViews();
        setupListeners();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        telephone = findViewById(R.id.telephone);
        complaintsText = findViewById(R.id.complaints_text);
        btnSubmit = findViewById(R.id.btn_submit);
        loadingProgress = findViewById(R.id.loading_progress);
        newImagePreview = findViewById(R.id.new_image_preview);
        newBtnSelectImage = findViewById(R.id.new_btn_select_image);
    }

    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
        btnSubmit.setOnClickListener(v -> handleSubmitFlow());
        newBtnSelectImage.setOnClickListener(v -> checkPermissionAndPickImage());
    }

    private void handleSubmitFlow() {
        if (!validateInput()) return;
        setLoadingState(true, "正在获取工单号...");

        // 步骤1: 获取工单号
        apiClient.generateWorkOrder("complaint", new ApiClient.OnCompleteListener<Response<String>>() {
            @Override
            public void onSuccess(Response<String> data) {
                if (data != null && "success".equals(data.getState())) {
                    String workOrderId = data.getData();
                    // 步骤2: (如果需要) 上传图片
                    if (selectedImageUri != null) {
                        setLoadingState(true, "正在上传图片...");
                        uploadImageThenSubmit(workOrderId);
                    } else {
                        // 如果没有图片，直接进入步骤3
                        setLoadingState(true, "正在提交投诉...");
                        submitComplaintData(workOrderId, null);
                    }
                } else {
                    setLoadingState(false, null);
                    Toast.makeText(ComplaintSuggestionActivity.this, "获取工单号失败: " + (data != null ? data.getError() : "未知错误"), Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void OnError(Throwable error) {
                setLoadingState(false, null);
                Log.e(TAG, "GenerateWorkOrder OnError: ", error);
                Toast.makeText(ComplaintSuggestionActivity.this, "网络错误，获取工单号失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean validateInput() {
        if (!DataValidator.isValidPhoneNumber(telephone.getText().toString())) {
            Toast.makeText(this, "电话号要求11位数字且第一位数字不为0", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!DataValidator.isNotEmpty(complaintsText.getText().toString())) {
            Toast.makeText(this, "投诉内容不得为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void uploadImageThenSubmit(final String workOrderId) {
        File imageFile = createTempFileFromUri(selectedImageUri);
        if (imageFile == null) {
            setLoadingState(false, null);
            Toast.makeText(this, "创建临时图片文件失败", Toast.LENGTH_SHORT).show();
            return;
        }
        String newFilename = workOrderId + "-complaints" + getFileExtension(selectedImageFileName);
        apiClient.uploadImage(imageFile, newFilename, new ApiClient.OnCompleteListener<Response<Object>>() {
            @Override
            public void onSuccess(Response<Object> data) {
                if (data != null && "success".equals(data.getState())) {
                    setLoadingState(true, "正在提交投诉...");
                    submitComplaintData(workOrderId, newFilename);
                } else {
                    setLoadingState(false, null);
                    Toast.makeText(ComplaintSuggestionActivity.this, data != null ? data.getError() : "图片上传失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void OnError(Throwable error) {
                setLoadingState(false, null);
                Log.e(TAG, "ImageUpload OnError: ", error);
                Toast.makeText(ComplaintSuggestionActivity.this, "网络错误，图片上传失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void submitComplaintData(String workOrderId, String imageId) {
        Complaint complaint = new Complaint(
                workOrderId,
                complaintsText.getText().toString(),
                imageId,
                telephone.getText().toString()
        );
        apiClient.submitComplaint(complaint, new ApiClient.OnCompleteListener<Response<Object>>() {
            @Override
            public void onSuccess(Response<Object> data) {
                setLoadingState(false, null);
                if (data != null && "success".equals(data.getState())) {
                    Toast.makeText(ComplaintSuggestionActivity.this, "投诉提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(ComplaintSuggestionActivity.this, data != null ? data.getError() : "投诉提交失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void OnError(Throwable error) {
                setLoadingState(false, null);
                Log.e(TAG, "ComplaintSubmit OnError: ", error);
                Toast.makeText(ComplaintSuggestionActivity.this, "网络错误，投诉提交失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setLoadingState(boolean isLoading, String message) {
        loadingProgress.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        btnSubmit.setEnabled(!isLoading);
        telephone.setEnabled(!isLoading);
        complaintsText.setEnabled(!isLoading);
        newBtnSelectImage.setEnabled(!isLoading);
        if (isLoading && message != null) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }

    // --- 图片处理辅助方法 ---
    private void checkPermissionAndPickImage() {
        String permission = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ?
                Manifest.permission.READ_MEDIA_IMAGES : Manifest.permission.READ_EXTERNAL_STORAGE;
        if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
            pickImageFromGallery();
        } else {
            requestPermissionLauncher.launch(permission);
        }
    }
    private void pickImageFromGallery() { pickImageLauncher.launch("image/*"); }
    private String getFileExtension(String filename) {
        if (filename == null) return "";
        int lastDotIndex = filename.lastIndexOf('.');
        return (lastDotIndex >= 0) ? filename.substring(lastDotIndex) : "";
    }
    private String getFileNameFromUri(Uri uri) {
        String fileName = null;
        if (uri.getScheme() != null && uri.getScheme().equals("content")) {
            try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex != -1) fileName = cursor.getString(nameIndex);
                }
            }
        }
        if (fileName == null) {
            fileName = uri.getPath();
            int cut = fileName.lastIndexOf('/');
            if (cut != -1) fileName = fileName.substring(cut + 1);
        }
        return fileName;
    }
    private File createTempFileFromUri(Uri uri) {
        try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
            if (inputStream == null) return null;
            File tempFile = new File(getCacheDir(), "temp_image_" + System.currentTimeMillis());
            try (OutputStream outputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[4 * 1024];
                int read;
                while ((read = inputStream.read(buffer)) != -1) outputStream.write(buffer, 0, read);
                outputStream.flush();
            }
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}